package com.yunfinal.api.service.db.dao;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.Db;

/**
 * 使用Jfinal 的SQL模版引擎，对SqlPara的参数map进行封装，方便API开发使用，
 * ActiveRecordPlugin 中记得放入配合模版
 * arp.addSqlTemplate("/sql/common.sql");
 * <p>
 * 例子
 * <pre>
 * public Object getCourseOrdersDetail(JSONObject kv) {
 * //获取购课记录的时间，编号等信息
 * FindKv findKv = FindKv.bySelect("id, ordernum, teachtype, createtime, subjectids");
 * //条件 UserKit是自建的工具
 * findKv.setCond(CondKv.by("studentid=", UserKit.getAccountId(kv)));
 * //排序 倒序
 * findKv.setOrderBy("createtime DESC");
 * //分页
 * findKv.setLimit(kv);
 * 继承BaseDao的子类（GenerateDao生成器生成）
 * List<Record> orderList = DaoCrmCourseorder.ME.find(findKv);
 * for (Record r : orderList) {
 * handerOrder(r);
 * }
 * return orderList;
 * }
 * </pre>
 *
 * @author 杜福忠
 */
public class FindKv extends Kv {

    public FindKv() {
        set("CondKvKit", CondKvKit.ME);
    }

    public static FindKv byCond(CondKv cond) {
        return new FindKv().setCond(cond);
    }

    public static FindKv bySelect(String select) {
        return new FindKv().setSelect(select);
    }

    public String getTable() {
        return getStr("table");
    }

    public FindKv setTable(String table) {
        set("table", table);
        return this;
    }

    public String getSelect() {
        return getStr("select");
    }

    public FindKv setSelect(String select) {
        set("select", select);
        return this;
    }

    public String getOrderBy() {
        return getStr("orderBy");
    }

    public FindKv setOrderBy(String orderBy) {
        set("orderBy", orderBy);
        return this;
    }

    public Kv getLimit() {
        return getAs("limit");
    }

    public FindKv setLimit(JSONObject kv) {
        Integer pageNumber = kv.getInteger("pageNumber");
        Integer pageSize = kv.getInteger("pageSize");
        setLimit(pageNumber, pageSize);
        return this;
    }

    public FindKv setLimit(Integer pageSize) {
        return setLimit(null, pageSize);
    }

    public FindKv setLimit(Integer pageNumber, Integer pageSize) {
        if (null == pageNumber) {
            pageNumber = 0;
        }
        if (null == pageSize) {
            pageSize = 200;
        }
        set("limit", Kv.by("pageNumber", pageNumber).set("pageSize", pageSize));
        return this;
    }

    protected Config getConfig() {
        return Db.use().getConfig();
    }

    public Kv getCond() {
        return getAs("cond");
    }

    public FindKv setCond(CondKv cond) {
        set("cond", cond);
        return this;
    }

}
